package olegroshka.src.com.bofa.olegroshka.datasource;

import java.util.Iterator;

import olegroshka.src.com.bofa.olegroshka.decorator.Decorator;
import olegroshka.src.com.bofa.olegroshka.decorator.Transformation;

public class TransformingDataSource implements DataSource<Object[]> {

	private final DataSource<Object[]> dataSource;
	private final Transformation[] transformations;
	
	
	public TransformingDataSource(
			DataSource<Object[]> dataSource,
			Transformation[] transformations) {
		this.dataSource = dataSource;
		this.transformations = transformations;
	}

	public Iterator<Object[]> iterator() {
		return new Iterator<Object[]>() {
			private final Iterator<Object[]> iterator = dataSource.iterator();
			
			public boolean hasNext() {
				return iterator.hasNext();
			}

			public Object[] next() {
				Object[] transformedRecord = null;
				Object[] record = iterator.next();
				if (record != null) {
					transformedRecord = new Object[transformations.length];
					for (int i = 0; i < transformations.length; i++) {
						Transformation transformation = transformations[i];
						Decorator<Object, Object> decorator = transformation.getDecorator();
						Object sourceElement = record[transformation.getSourceColumn()];
						transformedRecord[i] = decorator.decorate(sourceElement);
					}
				}
				
				return transformedRecord;
			}

			public void remove() {
				throw new UnsupportedOperationException();
			}
		};
	}

	public void begin() {
		dataSource.begin();
	}

	public void end() {
		dataSource.end();
	}

}
